import React, { useEffect, useState } from 'react';
import { Col, Row, Select } from 'antd';
import { api as apiMap, xhrGet } from '@/services';
import { TableOperate } from '@/components/SelfIcon';

import { getTempData } from '@/biz-components/_common/wrapXhr';

export interface SelectIconProps {
  onChange: (code: string) => void;
  value: string;
  api?: any;
  [propsName: string]: any;
}
const ref = React.createRef<any>();

const SelectIcon: React.FC<SelectIconProps> = ({ api, onChange, value, exraProps }) => {
  const [data, setData] = useState<any[]>([]);

  const [searchValue, setSearchValue] = useState<string | undefined>(undefined);

  useEffect(() => {
    if (api) {
      getTempData(api).then((result: any) => {
        setData(result);
      });
    } else {
      xhrGet(apiMap.dictValueList, {
        code: 'table_button',
      }).then((res: any) => {
        if (res?.success) {
          setData(res.result);
        }
      });
    }
  }, [api]);
  const handleIconClick = (code: string, node: any) => {
    onChange(code);
    ref?.current.blur();
  };

  const handleSearch = (likeValue: string) => {
    setSearchValue(likeValue);
  };

  return (
    <Select
      {...exraProps}
      ref={ref}
      value={value || ''}
      showSearch
      searchValue={searchValue}
      onSearch={handleSearch}
      dropdownRender={() => {
        return (
          <Row gutter={3} style={{ padding: 5 }}>
            {data.map((i: any) => {
              let background = 'white';

              if (i.code === value) {
                background = 'gray';
              }

              if (searchValue && i.code.includes(searchValue) ) {
                background = 'red';
              }

              return (
                <Col
                  span={2}
                  style={{
                    color: 'black',
                    fontSize: 24,
                    cursor: 'pointer',
                    background,
                    textAlign: 'center',
                  }}
                >
                  <TableOperate
                    onClick={() => handleIconClick(i.code, i)}
                    type={i.code}
                    text={i.name}
                    key={i.name}
                  />
                </Col>
              );
            })}
          </Row>
        );
      }}
    />
  );
};

export default SelectIcon;
